import axios from 'axios'
import { Notify, Loading } from 'vant';
// 创建axios实例
const service = axios.create({
    baseURL: '/api/1.0/web', // api的base_url
    // timeout: 20000 // 请求超时时间
})


// request拦截器
service.interceptors.request.use(config => {
    // localStorage.OriginalPageUrl = window.location.href;
    config.headers['OriginalPageUrl'] = window.location.href;

    if (config.method === 'get' && config.data && Object.keys(config.data).length > 0) {
        let strArr = []
        for (var key in config.data) {
            strArr.push(`${key}=${config.data[key]}`)
        }
        config.url += '?' + strArr.join('&')
    }

    if (config.headers.showLoading) {
        
    }
    // Do something before request is sent
    return config
}, error => {
    // Do something with request error
    console.log('axios request interceptors: ', error) // for debug
    return Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        
        /**
         * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
         * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
         */
        const res = response.data
        if (!!res.code) {
            if (res.needRedirect && res.redirectUrl) {
                //需要重定向
                window.location.href = res.redirectUrl
            }

            if (res.code !== 200) {
                let message = ''

                if (res.code === 14013) {
                    message = '请登录'
                    location.href = location.origin + '/#/hire/login'
                } else {
                    message = res.message
                }
                Notify(message)

                return res
            } else {
                return res
            }
        } else {
            Notify('服务异常，请稍候重试')
            return Promise.reject('error')
        }
    },
    error => {
        console.log('axios response interceptors: ', error) // for debug
        Notify({
            message: error,
            type: 'error',
            duration: 5 * 1000
        })

        return Promise.reject(error)
    }
)

export default service
